import { useTestResults } from '@/contexts/TestResultsContext';
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Device } from "react-native-ble-plx";
import BluetoothService from '../../utils/BluetoothService';
import CardiovascularParser, { CardiovascularMeasurement } from '../../utils/CardiovascularParser';
import ECGImageCarousel from './ECGImageCarousel';
import { useAudioPlayer } from 'expo-audio';

interface GuideTextComponentProps {
    type?: string
}

const CardiovascularDevice: React.FC = () => {
    // 心血管检测设备的视频
    // const player = useVideoPlayer(require('../../assets/videos/alcohol.mp4'), player => {
    //     player.loop = true;
    //     player.muted = true;
    //     player.play();
    // });

    // 状态管理
    const [isConnected, setIsConnected] = useState<boolean>(false);
    const [isMeasuring, setIsMeasuring] = useState<boolean>(false);
    const [measurement, setMeasurement] = useState<CardiovascularMeasurement | null | void>(null);
    const measurementRef = React.useRef<CardiovascularMeasurement | null | void>(null); // 保存最新的measurement用于自动保存
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [isAutoConnecting, setIsAutoConnecting] = useState<boolean>(false);
    const [lastUpdateTime, setLastUpdateTime] = useState<number>(0);
    const [autoSaveEnabled, setAutoSaveEnabled] = useState<boolean>(true);
    const [baselineValues, setBaselineValues] = useState<any>(null); // 暂时注释，未使用
    const [leadStatus, setLeadStatus] = useState<{
        RA: boolean; // RA导联脱落信息 (true:脱落)
        LA: boolean; // LA导联脱落信息 (true:脱落)
        LL: boolean; // LL导联脱落信息 (true:脱落)
    } | null>(null);
    const [showCompletionDialog, setShowCompletionDialog] = useState<boolean>(false);
    const throttleInterval = 100;
    const {addTestResult} = useTestResults();
    
    // 添加组件挂载状态跟踪
    const isMountedRef = React.useRef<boolean>(true);
    
    // 使用 useAudioPlayer hook 创建音频播放器
    const audioSource = require('../../assets/mp3/notice.mp3');
    const player = useAudioPlayer(audioSource);

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };

    // 判断心血管检测是否完成
    const isCardiovascularTestComplete = (measurement: any): boolean => {
        if (!measurement || typeof measurement.value !== 'object') return false;
        // 心血管检测完成条件：有心率、血氧、血压和HRV/心康指数数据
        const hasHeartRate = measurement.value.heartRate !== undefined && measurement.value.heartRate > 0;
        const hasSpo2 = measurement.value.spo2 !== undefined && measurement.value.spo2 > 0;
        const hasBloodPressure = (measurement.value.systolic !== undefined && measurement.value.systolic > 0) || 
                             (measurement.value.diastolic !== undefined && measurement.value.diastolic > 0);
        const hasHRV = measurement.value.hrv !== undefined || measurement.value.st !== undefined;
        
        return hasHeartRate && hasSpo2 && (hasBloodPressure || hasHRV);
    };

    const handleTestComplete = () => {
        // 显示检测完成提示对话框
        setShowCompletionDialog(true);
        // 播放完成提示音
        playNotificationSound();
    };

    const finishTest = () => {
        setShowCompletionDialog(false);
    };

    // 设备配置
    const deviceName = "心血管检测";
    // 使用useMemo优化数组依赖项
    const deviceNamePrefix = React.useMemo(() => ["VSE Detector"], []);
    const serviceUUID = CardiovascularParser.SERVICE_UUID;
    const commandServiceUUID = CardiovascularParser.SERVICE_UUID;
    const commandCharacteristic = CardiovascularParser.COMMAND_CHARACTERISTIC;
    // const startCommand = CardiovascularParser.getStartCommand(); // 暂时注释，未使用
    const stopCommand = CardiovascularParser.getStopCommand();
    // const startHRVCommand = CardiovascularParser.START_HRV_PRESSURE_COMMAND; // 暂时注释，未使用
    const withResp = false;

    // 原子方法 - 查找设备
    const findDevice = React.useCallback(async (prefix: string[] | string): Promise<Device> => {
        if (!BluetoothService.isReady()) {
            throw new Error('蓝牙服务尚未初始化，请稍后再试');
        }

        const device = await BluetoothService.findDeviceByNamePrefix(
            null,
            prefix
        );
        if (!device) {
            throw new Error(`设备查找失败: 未找到名称以${prefix}开头的设备`);
        }
        return device;
    }, []); // 无外部依赖

    // 原子方法 - 连接设备
    const connect = React.useCallback(async (device: Device): Promise<void> => {
        if (!BluetoothService.isReady()) {
            throw new Error('蓝牙服务尚未初始化，请稍后再试');
        }

        const connectionOptions = {
            autoConnect: false,
            connectionPriority: 1,
            shouldEnableNotificationWhenServiceDiscovered: true
        };
        try {
            await BluetoothService.connectDevice(
                device.id,
                [serviceUUID],
                connectionOptions
            );
            setIsConnected(true);
            await new Promise(resolve => setTimeout(resolve, 100));
        } catch (err) {
            throw new Error(`连接失败: ${err}`);
        }
    }, [setIsConnected, serviceUUID]); // 添加缺失的serviceUUID依赖项

    // 当前测量阶段状态
    const [currentStage, setCurrentStage] = useState<'idle' | 'hr_spo2' | 'blood_pressure' | 'ecg'>('idle');
    const [isSkipped, setIsSkipped] = useState<{ [key: string]: boolean }>({});
    
    // 图片弹窗状态
    const [showImageModal, setShowImageModal] = useState<boolean>(false);
    const [currentImage, setCurrentImage] = useState<number | null>(null);
    const [imageShown30, setImageShown30] = useState<boolean>(false); // 进度一半图片是否已显示
    const [imageShown80, setImageShown80] = useState<boolean>(false); // 快结束图片是否已显示
    // 使用useRef存储定时器ID，避免重复触发
    const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);

    // ECG图片数据
    const ecgImages = [
        { source: require('../../assets/images/ecg/all.jpg'), title: '全身导联位置' },
        { source: require('../../assets/images/ecg/left-arm.jpg'), title: '左臂血压袖带位置' },
        { source: require('../../assets/images/ecg/left-foot.jpg'), title: '左脚导联位置' },
        { source: require('../../assets/images/ecg/left-hand.jpg'), title: '左手导联位置' },
        { source: require('../../assets/images/ecg/right-hand.jpg'), title: '右手导联位置' },
    ];

    // 心血管设备特定的数据订阅逻辑
    const subscribeToData = async () => {
        // 重置状态
        setCurrentStage('idle');
        setIsSkipped({});

        // 开始按顺序测量：先心率血氧，再血压，最后HRV
        await startHeartRateSpO2Measurement();
    };

    // 跳过当前测量阶段
    const skipCurrentStage = async () => {
        const BP_UUID = CardiovascularParser.BLOOD_PRESSURE_CHARACTERISTIC.toLowerCase();
        const HR_UUID = CardiovascularParser.HEART_RATE_CHARACTERISTIC.toLowerCase();
        const ECG_UUID = CardiovascularParser.ECG_CHARACTERISTIC.toLowerCase();

        setIsSkipped(prev => ({...prev, [currentStage]: true}));

        try {
            // 根据当前阶段决定下一步操作
            switch (currentStage) {
                case 'hr_spo2':
                    // 取消HR/SpO2订阅
                    try {
                        BluetoothService.removeNotifyRequest(serviceUUID, HR_UUID);
                    } catch (err) {
                        console.warn('取消HR/SpO2订阅时出错:', err);
                    }
                    // 直接调用血压测量函数
                    await startBloodPressureMeasurement();
                    break;
                case 'blood_pressure':
                    // 立即设置跳过标记并切换阶段，确保UI响应
                    setIsSkipped(prev => ({...prev, blood_pressure: true}));

                    try {
                        console.log('开始跳过血压测量阶段...');

                        // 安全地取消BP订阅，即使失败也继续流程
                        try {
                            BluetoothService.removeNotifyRequest(serviceUUID, BP_UUID);
                            console.log('成功取消BP订阅');
                        } catch (removeError) {
                            console.warn('取消BP订阅时出错，但继续执行:', removeError);
                        }

                        // 安全地发送停止命令
                        if (commandServiceUUID && commandCharacteristic) {
                            try {
                                await BluetoothService.writeCommand(
                                    commandServiceUUID,
                                    commandCharacteristic,
                                    CardiovascularParser.STOP_BLOOD_PRESSURE_COMMAND,
                                    withResp
                                );
                                console.log('成功发送血压停止命令');
                                // 增加延迟时间，确保设备充分响应
                                await new Promise(resolve => setTimeout(resolve, 500));
                            } catch (commandError) {
                                console.warn('发送停止命令时出错，但继续执行:', commandError);
                            }
                        }

                        // 强制保持连接状态
                        setIsConnected(true);

                        // 直接调用HRV测量函数
                        await startHRVMeasurement();

                        console.log('血压测量阶段跳过完成，成功进入HRV测量阶段');
                    } catch (bpSkipError) {
                        console.error('跳过血压测量阶段时发生严重错误:', bpSkipError);
                        // 确保状态正确，无论如何都保持UI可用
                        setCurrentStage('ecg');
                        setIsConnected(true);
                    }
                    break;
                case 'ecg':
                    // 取消ECG订阅
                    try {
                        BluetoothService.removeNotifyRequest(serviceUUID, ECG_UUID);
                    } catch (err) {
                        console.warn('取消ECG订阅时出错:', err);
                    }
                    // 发送停止命令，确保设备正常停止测量
                    if (commandServiceUUID && commandCharacteristic) {
                        await BluetoothService.writeCommand(
                            commandServiceUUID,
                            commandCharacteristic,
                            stopCommand
                        );
                    }
                    // 结束测量
                    setCurrentStage('idle');
                    // 正常结束测量过程，设置isMeasuring为false
                    setIsMeasuring(false);
                    // 保存测试结果到上下文
                    if (measurement) {
                        const normalizedMeasurement = createNormalizedCardiovascularMeasurement(measurement);
                        if (normalizedMeasurement) {
                            addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);
                        }
                    }
                    break;
            }
        } catch (error) {
            console.error('跳过当前阶段失败:', error);
            // 保持连接状态，避免尝试重新连接
            setIsConnected(true);
        }
    };

    // 更新measurement并同步ref的包装函数
    const updateMeasurement = React.useCallback((updater: any) => {
        setMeasurement((prev) => {
            const next = typeof updater === 'function' ? updater(prev) : updater;
            measurementRef.current = next;
            return next;
        });
    }, []);

    // 合并测量数据的辅助函数
    const mergeMeasurement = (prev: any, next: any): any => {
        const prevValue = (prev && typeof prev.value === 'object' && !Array.isArray(prev.value)) ? prev.value : {};
        const nextValue = (typeof next.value === 'object' && !Array.isArray(next.value)) ? next.value : {};

        // 安全合并值，确保不会丢失任何重要数据
        // 首先创建一个空对象
        const mergedValue: any = {};

        // 将所有prevValue的属性复制到mergedValue
        Object.keys(prevValue).forEach(key => {
            mergedValue[key] = prevValue[key];
        });

        // 然后只复制nextValue中有实际值的属性，避免覆盖已有数据
        // 注意：只有当nextValue中的值不是undefined、null或空字符串时才更新
        Object.keys(nextValue).forEach(key => {
            const nextVal = nextValue[key];
            // 只有当新值有效时才更新
            if (nextVal !== undefined && nextVal !== null && nextVal !== '') {
                mergedValue[key] = nextVal;
            }
        });

        // 确保所有重要指标都存在（使用更严格的判断）
        // 心率和血氧
        if (prevValue.heartRate !== undefined && nextValue.heartRate === undefined) {
            mergedValue.heartRate = prevValue.heartRate;
        }
        if (prevValue.spo2 !== undefined && nextValue.spo2 === undefined) {
            mergedValue.spo2 = prevValue.spo2;
        }
        // 血压相关
        if (prevValue.systolic !== undefined && nextValue.systolic === undefined) {
            mergedValue.systolic = prevValue.systolic;
        }
        if (prevValue.diastolic !== undefined && nextValue.diastolic === undefined) {
            mergedValue.diastolic = prevValue.diastolic;
        }
        if (prevValue.meanPressure !== undefined && nextValue.meanPressure === undefined) {
            mergedValue.meanPressure = prevValue.meanPressure;
        }
        if (prevValue.pulse !== undefined && nextValue.pulse === undefined) {
            mergedValue.pulse = prevValue.pulse;
        }
        // 特殊指标
        if (prevValue.stressIndex !== undefined && nextValue.stressIndex === undefined) {
            mergedValue.stressIndex = prevValue.stressIndex;
        }
        if (prevValue.heartAttackIndex !== undefined && nextValue.heartAttackIndex === undefined) {
            mergedValue.heartAttackIndex = prevValue.heartAttackIndex;
        }

        const prevUnit = (prev && typeof prev.unit === 'object') ? prev.unit : {};
        const nextUnit = (typeof next.unit === 'object') ? next.unit : {};
        const mergedUnit = (Object.keys(prevUnit).length || Object.keys(nextUnit).length)
            ? {...prevUnit, ...nextUnit}
            : (typeof next.unit === 'string' ? next.unit : '');

        // 合并HRV结果
        const mergedHRVResult = {
            ...(prev?.hrvResult || {}),
            ...(next?.hrvResult || {})
        };

        // 保留ST值（如果有）
        const stValues = next?.stValues !== undefined ? next.stValues : prev?.stValues;

        // 处理导联状态（如果有）
        if (next?.leadStatus) {
            setLeadStatus(next.leadStatus);
        }

        return {
            value: mergedValue,
            unit: mergedUnit,
            rawData: next.rawData,
            timestamp: next.timestamp,
            hrvResult: Object.keys(mergedHRVResult).length > 0 ? mergedHRVResult : undefined,
            stValues
        };
    };

    // 规范化心血管测量数据，确保字段名与examination.tsx期望的一致
    const normalizeCardiovascularValue = (value: any) => {
        if (!value || typeof value !== 'object') {
            return {};
        }

        // 辅助函数：安全获取值，支持多种键名变体，不会丢失0值
        const getValue = (primaryKey: string, altKeys: string[] = []) => {
            if (value[primaryKey] !== undefined && value[primaryKey] !== null) {
                return value[primaryKey];
            }
            for (const key of altKeys) {
                if (value[key] !== undefined && value[key] !== null) {
                    return value[key];
                }
            }
            return undefined;
        };

        return {
            // 心率 - 支持多种键名变体
            heartRate: getValue('heartRate', ['HeartRate', 'pulse']),
            // 血氧 - 支持多种键名变体
            spo2: getValue('spo2', ['SpO2', 'oxygenSaturation']),
            // 收缩压
            systolic: getValue('systolic'),
            // 舒张压
            diastolic: getValue('diastolic'),
            // 压力指数 - hrv对应stressIndex
            stressIndex: getValue('stressIndex', ['hrv']),
            // 心康指数 - st对应heartAttackIndex
            heartAttackIndex: getValue('heartAttackIndex', ['st', 'myocardialInfarctionIndex']),
            // 保留其他可能需要的字段
            meanPressure: getValue('meanPressure'),
            pulse: getValue('pulse'),
            pi: getValue('pi'),
            hrv: getValue('hrv'),
            st: getValue('st')
        };
    };

    // 创建规范化的心血管测量数据对象
    const createNormalizedCardiovascularMeasurement = (measurement: any) => {
        if (!measurement) {
            return null;
        }

        const normalizedValue = normalizeCardiovascularValue(measurement.value);
        // 合并现有的value和规范化后的value，确保不丢失任何字段
        const mergedValue = {
            ...(measurement.value || {}),
            ...normalizedValue
        };
        
        return {
            ...measurement,
            value: mergedValue
        };
    };

    // 组合方法 - 完整连接流程
    const connectDevice = React.useCallback(async (prefix: string[] | string, isAutoConnect: boolean = false): Promise<void> => {
        // 如果已经连接，直接返回
        if (isConnected) {
            console.log('设备已连接，跳过连接流程');
            return;
        }

        let retryCount = 0;
        const maxRetries = isAutoConnect ? 30 : 3;

        // 手动连接时显示加载状态
        if (!isAutoConnect) {
            setIsLoading(true);
        }

        while (retryCount < maxRetries) {
            // 检查组件是否已卸载，如果已卸载则退出循环
            if (!isMountedRef.current) {
                console.log('组件已卸载，停止连接尝试');
                return;
            }
            
            try {
                console.log(`尝试连接设备 (第${retryCount + 1}次)...`);

                const device = await findDevice(prefix);
                // 在连接前再次检查组件是否已卸载
                if (!isMountedRef.current) {
                    console.log('组件已卸载，停止连接');
                    return;
                }
                
                await connect(device);

                console.log('设备连接成功');
                return;

            } catch (err) {
                retryCount++;
                const errorMessage = err instanceof Error ? err.message : String(err);
                console.log(`连接尝试 ${retryCount} 失败:`, errorMessage);

                if (retryCount >= maxRetries) {
                    console.log('连接最终失败');
                } else {
                    // 重试前等待
                    await new Promise(resolve => setTimeout(resolve, isAutoConnect ? 3000 : 1000));
                }
            }
        }

        // 最终清理加载状态
        if (!isAutoConnect && isMountedRef.current) {
            setIsLoading(false);
        }
    }, [findDevice, connect, isConnected, setIsLoading]); // 添加useCallback依赖项

    // 断开设备 - 暂时注释，未使用
    // const disconnectDevice = async () => {
    //     try {
    //         setIsLoading(true);
    //         await BluetoothService.removeAllNotifyRequests();
    //         await BluetoothService.disconnectDevice();
    //         setIsConnected(false);
    //         setIsMeasuring(false);
    //         setMeasurement(null);
    //     } catch (err) {
    //         console.error(`断开连接失败: ${err}`);
    //     } finally {
    //         setIsLoading(false);
    //     }
    // };

    // 开始测量
    const startMeasurement = async () => {
        if (!isConnected) return;

        try {
            // 重置解析器数据，准备新的测量
            CardiovascularParser.resetData();
            setIsLoading(true);
            await subscribeToData();
            // if (commandServiceUUID && commandCharacteristic) {
            //     await BluetoothService.writeCommand(
            //         commandServiceUUID,
            //         commandCharacteristic,
            //         startCommand,
            //         withResp
            //     );
            // }
            setIsMeasuring(true);
        } catch (err) {
            console.error(`开始测量失败: ${err}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 开始心率/血氧测量
    const startHeartRateSpO2Measurement = async () => {
        if (!isConnected || isLoading) return;

        try {
            setIsLoading(true);
            setCurrentStage('hr_spo2');

            // 重置样本数组
            const hrSamples: number[] = [];
            const spo2Samples: number[] = [];

            // 直接订阅心率/血氧通道
            const HR_UUID = CardiovascularParser.HEART_RATE_CHARACTERISTIC.toLowerCase();

            // 首先取消可能存在的订阅
            try {
                BluetoothService.removeNotifyRequest(serviceUUID, HR_UUID);
            } catch (err) {
                console.warn('取消现有HR/SpO2订阅时出错:', err);
            }

            await BluetoothService.addNotifyRequest(
                serviceUUID,
                HR_UUID,
                (data: string) => {
                    try {
                        const parsed = CardiovascularParser.parseDataWithMeta
                            ? CardiovascularParser.parseDataWithMeta(data, {characteristicUUID: HR_UUID})
                            : CardiovascularParser.parseData(data);
                        if (parsed && typeof parsed.value === 'object') {
                            const hr = (parsed.value as any).heartRate;
                            const s = (parsed.value as any).spo2;

                            // 收集有效样本
                            if (typeof hr === 'number' && hr > 0 && hr <= 220) {
                                hrSamples.push(hr);
                            }
                            if (typeof s === 'number' && s > 0 && s <= 100) {
                                spo2Samples.push(s);
                            }

                            // 累计到10个有效样本后，计算均值（去除最高最低两个）
                            if (hrSamples.length >= 10 || spo2Samples.length >= 10) {
                                // 计算均值函数：去除最高最低两个值后求平均
                                const calculateAverage = (arr: number[]) => {
                                    if (!arr.length) return undefined;
                                    // 复制数组并排序
                                    const sorted = [...arr].sort((a, b) => a - b);
                                    // 如果样本数大于4，去除最高最低两个值
                                    const filtered = arr.length > 4
                                        ? sorted.slice(2, -2) // 去除前两个和后两个
                                        : arr; // 样本数少于等于4时直接使用全部样本
                                    return Math.round(filtered.reduce((a, b) => a + b, 0) / filtered.length);
                                };

                                const avgHR = calculateAverage(hrSamples);
                                const avgSpO2 = calculateAverage(spo2Samples);

                                const averaged = {
                                    value: {
                                        ...(typeof avgHR === 'number' ? {heartRate: avgHR} : {}),
                                        ...(typeof avgSpO2 === 'number' ? {spo2: avgSpO2} : {}),
                                    },
                                    unit: {
                                        ...(typeof avgHR === 'number' ? {heartRate: 'BPM'} : {}),
                                        ...(typeof avgSpO2 === 'number' ? {spo2: '%'} : {}),
                                    },
                                    rawData: '',
                                    timestamp: new Date().toISOString(),
                                };

                                // 保存均值结果
                                updateMeasurement((prev: any) => mergeMeasurement(prev, averaged));
                                // 取消HR/SpO2订阅
                                BluetoothService.removeNotifyRequest(serviceUUID, HR_UUID);

                                // 自动进入下一阶段：血压测量
                                startBloodPressureMeasurement();
                            }

                            // 实时更新UI
                            const currentTime = Date.now();
                            if (currentTime - lastUpdateTime >= throttleInterval) {
                                // 获取合并后的完整数据
                                const merged = mergeMeasurement(measurementRef.current, parsed);
                                updateMeasurement(merged);
                                setLastUpdateTime(currentTime);
                                if (autoSaveEnabled) {
                                    // 使用合并后的完整数据进行规范化并保存
                                    const normalizedMeasurement = createNormalizedCardiovascularMeasurement(merged);
                                    if (normalizedMeasurement) {
                                        addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);
                                    }
                                }
                            }
                        }
                    } catch (e) {
                        console.log(`心率/血氧数据解析错误: ${e}`);
                    }
                }
            );
        } catch (error) {
            console.error('开始心率/血氧测量失败:', error);
        } finally {
            setIsLoading(false);
        }
    };

    // 开始血压测量
    const startBloodPressureMeasurement = async () => {
        if (!isConnected || isLoading) return;

        try {
            setIsLoading(true);
            setCurrentStage('blood_pressure');

            const BP_UUID = CardiovascularParser.BLOOD_PRESSURE_CHARACTERISTIC.toLowerCase();

            // 首先取消可能存在的订阅
            try {
                BluetoothService.removeNotifyRequest(serviceUUID, BP_UUID);
            } catch (err) {
                console.warn('取消现有BP订阅时出错:', err);
            }

            // 订阅血压通道
            await BluetoothService.addNotifyRequest(
                serviceUUID,
                BP_UUID,
                (data: string) => {
                    try {
                        const parsed = CardiovascularParser.parseDataWithMeta
                            ? CardiovascularParser.parseDataWithMeta(data, {characteristicUUID: BP_UUID})
                            : CardiovascularParser.parseData(data);
                        if (parsed && typeof parsed.value === 'object') {
                            // 如果包含最终血压结果（收缩、舒张有其一）则认为完成
                            const hasFinalBP = ('systolic' in parsed.value) || ('diastolic' in parsed.value);
                            if (hasFinalBP) {
                                // 取消BP订阅
                                BluetoothService.removeNotifyRequest(serviceUUID, BP_UUID);
                                // 开始心电测量
                                startHRVMeasurement();
                            }
                            // 正常上报保存
                            const currentTime = Date.now();
                            if (currentTime - lastUpdateTime >= throttleInterval) {
                                // 获取合并后的完整数据
                                const merged = mergeMeasurement(measurementRef.current, parsed);
                                updateMeasurement(merged);
                                setLastUpdateTime(currentTime);
                                if (autoSaveEnabled) {
                                    // 使用合并后的完整数据进行规范化并保存
                                    const normalizedMeasurement = createNormalizedCardiovascularMeasurement(merged);
                                    if (normalizedMeasurement) {
                                        addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);
                                    }
                                }
                            }
                        }
                    } catch (e) {
                        console.log(`BP数据解析错误: ${e}`);
                    }
                }
            );

            // 发送血压开始命令
            await BluetoothService.writeCommand(
                commandServiceUUID,
                commandCharacteristic,
                CardiovascularParser.START_BLOOD_PRESSURE_COMMAND,
                withResp
            );

            console.log('血压测量已启动：已订阅BP通道并发送开始命令');
        } catch (error) {
            console.error('开始血压测量失败:', error);
        } finally {
            setIsLoading(false);
        }
    };

    // 开始HRV/心电测量
    const startHRVMeasurement = async () => {
        if (!isConnected || isLoading) return;

        try {
            // 不重置解析器数据，以保持进度值的连续性
            // CardiovascularParser.resetData();
            setIsLoading(true);
            setCurrentStage('ecg');
            // 重置导联状态
            setLeadStatus(null);
            // 重置图片弹窗状态
            // 清除可能存在的定时器
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
            }
            setImageShown30(false);
            setImageShown80(false);
            setShowImageModal(false);
            setCurrentImage(null);

            const BP_UUID = CardiovascularParser.BLOOD_PRESSURE_CHARACTERISTIC.toLowerCase();
            const ECG_UUID = CardiovascularParser.ECG_CHARACTERISTIC.toLowerCase();

            // 首先取消可能存在的订阅
            try {
                BluetoothService.removeNotifyRequest(serviceUUID, BP_UUID);
                BluetoothService.removeNotifyRequest(serviceUUID, ECG_UUID);
            } catch (err) {
                console.warn('取消现有订阅时出错:', err);
            }

            // 订阅心电通道
            await BluetoothService.addNotifyRequest(
                serviceUUID,
                ECG_UUID,
                (data: string) => {
                    try {
                        const currentTime = Date.now();
                        if (currentTime - lastUpdateTime >= throttleInterval) {
                            // 移除重复的导联状态解析逻辑，因为这部分已经在mergeMeasurement函数中通过解析器处理
                            // 这样避免了双重解析导致的状态不一致问题

                            const parsed = CardiovascularParser.parseDataWithMeta
                                ? CardiovascularParser.parseDataWithMeta(data, {characteristicUUID: ECG_UUID})
                                : CardiovascularParser.parseData(data);
                            if (parsed) {
                                // 获取合并后的完整数据
                                const merged = mergeMeasurement(measurementRef.current, parsed);
                                updateMeasurement(merged);
                                setLastUpdateTime(currentTime);
                                
                                // 检查进度并触发图片弹窗
                                if (merged && typeof merged.value === 'object' && !Array.isArray(merged.value)) {
                                    const progress = merged.value.progress;
                                    if (typeof progress === 'number') {
                                        // 进度一半左右（45-55%）弹出图片1
                                        if (!imageShown30 && progress == 45) {
                                            // 清除可能存在的旧定时器
                                            if (timeoutRef.current) {
                                                clearTimeout(timeoutRef.current);
                                            }
                                            
                                            setCurrentImage(1);
                                            setShowImageModal(true);
                                            setImageShown30(true);
                                            
                                            // 1秒后自动关闭，使用ref存储定时器ID
                                            timeoutRef.current = setTimeout(() => {
                                                setShowImageModal(false);
                                                timeoutRef.current = null;
                                            }, 1000);
                                        }
                                        // 快结束时（85-95%）弹出图片2
                                        if (!imageShown80 && progress == 85) {
                                            // 清除可能存在的旧定时器
                                            if (timeoutRef.current) {
                                                clearTimeout(timeoutRef.current);
                                            }
                                            
                                            setCurrentImage(2);
                                            setShowImageModal(true);
                                            setImageShown80(true);
                                            
                                            // 1秒后自动关闭，使用ref存储定时器ID
                                            timeoutRef.current = setTimeout(() => {
                                                setShowImageModal(false);
                                                timeoutRef.current = null;
                                            }, 1000);
                                        }
                                    }
                                }
                                
                                if (autoSaveEnabled) {
                                    // 使用合并后的完整数据进行规范化并保存
                                    const normalizedMeasurement = createNormalizedCardiovascularMeasurement(merged);
                                    if (normalizedMeasurement) {
                                        addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);
                                    }
                                }
                            }
                        }
                    } catch (e) {
                        console.log(`心电数据解析错误: ${e}`);
                    }
                }
            );

            // 向血压通道发送0x45命令
            await BluetoothService.writeCommand(
                commandServiceUUID,
                commandCharacteristic,
                CardiovascularParser.START_HRV_COMMAND, // 直接发送0x45命令
                withResp
            );

            console.log('HRV测量已启动：已订阅ECG通道并向BP通道发送0x45命令');
        } catch (error) {
            console.error('开始HRV测量失败:', error);
        } finally {
            setIsLoading(false);
        }
    };

    // 停止测量
    const stopMeasurement = async () => {
        if (!isConnected) return;

        try {
            setIsLoading(true);
            const command = stopCommand;
            if (commandServiceUUID && commandCharacteristic) {
                await BluetoothService.writeCommand(
                    commandServiceUUID,
                    commandCharacteristic,
                    command
                );
            }
            setIsMeasuring(false);

            // 保存测试结果到上下文
            if (measurement) {
                // 保存规范化后的综合数据作为Cardiovascular类型，确保字段名统一
                const normalizedMeasurement = createNormalizedCardiovascularMeasurement(measurement);
                if (normalizedMeasurement) {
                    addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);
                    
                    // 检查是否完成所有测量项目
                    if (isCardiovascularTestComplete(measurement)) {
                        // 显示检测完成提示
                        handleTestComplete();
                    }
                }
            }
        } catch (err) {
            console.error(`停止测量失败: ${err}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 组件挂载时自动连接设备
    useEffect(() => {
        let isMounted = true;
        let autoConnectTimeout: ReturnType<typeof setTimeout>;

        const performAutoConnect = async () => {
            try {
                // 检查组件是否仍然挂载且未连接
                if (!isMounted || isConnected) {
                    return;
                }

                // 检查蓝牙服务是否准备就绪
                if (!BluetoothService.isReady()) {
                    console.log('蓝牙服务未准备就绪，跳过自动连接');
                    return;
                }

                console.log('开始自动连接设备:', deviceNamePrefix);
                setIsAutoConnecting(true);
                await connectDevice(deviceNamePrefix, true);
            } catch (err) {
                console.log('自动连接失败:', err);
            } finally {
                if (isMounted) {
                    setIsAutoConnecting(false);
                }
            }
        };

        // 延迟执行自动连接
        autoConnectTimeout = setTimeout(performAutoConnect, 1500);

        return () => {
            isMounted = false;
            if (autoConnectTimeout) {
                clearTimeout(autoConnectTimeout);
            }
        };
    }, [connectDevice, deviceNamePrefix, isConnected]); // 修复依赖项

    // 蓝牙状态监听
    useEffect(() => {
        const stateSubscription = BluetoothService.addStateListener((state) => {
            if (state === 'PoweredOff') {
                console.error('蓝牙已关闭，请打开蓝牙后重试');
                setIsConnected(false);
                setIsMeasuring(false);
            }
        });

        return () => {
            stateSubscription.remove();
        };
    }, [setIsConnected, setIsMeasuring]); // 添加依赖项

    // 组件卸载时的清理
    useEffect(() => {
        return () => {
            // 标记组件已卸载
            isMountedRef.current = false;
            
            const cleanup = async () => {
                try {
                    console.log('组件卸载，清理蓝牙连接');
                    await BluetoothService.removeAllNotifyRequests();
                    await BluetoothService.disconnectDevice();
                } catch (err) {
                    console.log('清理连接时出错:', err);
                }
            };

            cleanup();
        };
    }, []);

    // 渲染心血管设备特定的UI
    // 进度状态组件 - 用于在卡片中显示测量状态
    const StageStatus = ({stageKey, label}: { stageKey: string, label: string }) => {
        const isCurrentStage = currentStage === stageKey;
        const isCompleted = currentStage && currentStage !== stageKey && stages.findIndex(s => s.key === currentStage) > stages.findIndex(s => s.key === stageKey);
        const isSkippedStage = isSkipped && isSkipped[stageKey];

        let statusText = '';
        let statusStyle = styles.statusIdle;

        if (isSkippedStage) {
            statusText = '已跳过';
            statusStyle = styles.statusSkipped;
        } else if (isCurrentStage) {
            statusText = '测量中';
            statusStyle = styles.statusMeasuring;
        } else if (isCompleted) {
            statusText = '已完成';
            statusStyle = styles.statusCompleted;
        }

        return (
            <View style={styles.stageStatusContainer}>
                <Text style={styles.stageLabel}>{label}</Text>
                {statusText ? (
                    <View style={[styles.statusIndicatorSmall, statusStyle]}>
                        <Text style={styles.statusTextSmall}>{statusText}</Text>
                    </View>
                ) : null}
            </View>
        );
    };

    // 定义测量阶段
    const stages = [
        {key: 'hr_spo2', label: '心率/血氧测量'},
        {key: 'blood_pressure', label: '血压测量'},
        {key: 'ecg', label: '心电测量'}
    ];

    const renderResult = () => {
        const isObjectValue = measurement && typeof measurement.value === 'object' && !Array.isArray(measurement.value);

        // 总是显示带重测按钮的数据卡片，无论是否有数据
        return (
            <>
                <View style={styles.dataGrid}>
                    <View style={styles.dataCard}>
                        <StageStatus stageKey="hr_spo2" label="心率/血氧"/>
                        <View style={styles.combinedData}>
                            <Text style={styles.dataValue}>
                                {isObjectValue && typeof measurement.value.heartRate === 'number' ? `${measurement.value.heartRate}` : '--'}
                                <Text style={styles.unitSmall}> BPM</Text>
                            </Text>
                            <Text style={styles.separator}>/</Text>
                            <Text style={styles.dataValue}>
                                {isObjectValue && typeof measurement.value.spo2 === 'number' ? `${measurement.value.spo2}` : '--'}
                                <Text style={styles.unitSmall}> %</Text>
                            </Text>
                        </View>
                        <View style={styles.cardActions}>
                            {currentStage === 'hr_spo2' && (
                                <TouchableOpacity
                                    style={[styles.skipButton, styles.cardButton]}
                                    onPress={skipCurrentStage}
                                >
                                    <Text style={styles.skipButtonText}>跳过</Text>
                                </TouchableOpacity>
                            )}
                            <TouchableOpacity
                                style={[styles.retestButton, styles.cardButton, {marginLeft: currentStage === 'hr_spo2' ? 10 : 0}]}
                                onPress={() => {
                                    startHeartRateSpO2Measurement();
                                }}
                            >
                                <Text style={styles.retestButtonText}>重测</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.dataCard}>
                        <StageStatus stageKey="blood_pressure" label="血压"/>
                        <Text style={styles.dataValue}>
                            {isObjectValue && (typeof measurement.value.systolic === 'number' || typeof measurement.value.diastolic === 'number')
                                ? `${isObjectValue && typeof measurement.value.systolic === 'number' ? measurement.value.systolic : '--'}/${isObjectValue && typeof measurement.value.diastolic === 'number' ? measurement.value.diastolic : '--'}`
                                : '--/--'}
                            <Text style={styles.unitSmall}> mmHg</Text>
                        </Text>
                        {isObjectValue && typeof measurement.value.cuffPressure === 'number' && (
                            <Text style={styles.cuffText}>
                                实时袖带: {measurement.value.cuffPressure}
                                <Text style={styles.unitSmall}> mmHg</Text>
                            </Text>
                        )}
                        <View style={styles.cardActions}>
                            {currentStage === 'blood_pressure' && (
                                <TouchableOpacity
                                    style={[styles.skipButton, styles.cardButton]}
                                    onPress={skipCurrentStage}
                                >
                                    <Text style={styles.skipButtonText}>跳过</Text>
                                </TouchableOpacity>
                            )}
                            <TouchableOpacity
                                style={[styles.retestButton, styles.cardButton, {marginLeft: currentStage === 'blood_pressure' ? 10 : 0}]}
                                onPress={() => {
                                    startBloodPressureMeasurement();
                                }}
                            >
                                <Text style={styles.retestButtonText}>重测</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.dataCard}>
                        <StageStatus stageKey="ecg" label="压力指数 / 心康指数"/>
                        <View style={styles.combinedData}>
                            <Text style={styles.dataValue}>
                                {isObjectValue && measurement.value.hrv !== undefined && measurement.value.hrv !== null ? measurement.value.hrv.toFixed(2) : '--'}
                            </Text>
                            <Text style={styles.separator}>/</Text>
                            <Text style={styles.dataValue}>
                                {isObjectValue && measurement.value.st !== undefined && measurement.value.st !== null
                                    ? measurement.value.st.toFixed(2)
                                    : '--'}
                                <Text style={styles.unitSmall}> mV</Text>
                            </Text>
                        </View>
                        {leadStatus && Object.keys(leadStatus).length > 0 && (
                            <View style={{position: 'absolute', top: 10, right: 10, flexDirection: 'row'}}>
                                {Object.entries(leadStatus).map(([lead, isDisconnected]) => (
                                    <View key={lead} style={{marginLeft: 8}}>
                                        <View style={{
                                            width: 12,
                                            height: 12,
                                            borderRadius: 6,
                                            backgroundColor: isDisconnected ? '#F44336' : '#4CAF50'
                                        }}/>
                                        <Text style={styles.cuffText}>{lead}</Text>
                                    </View>
                                ))}
                            </View>
                        )}
                        {isObjectValue && measurement.value.progress !== undefined && (
                            <Text style={styles.cuffText}>
                                测量进度: {`${measurement.value.progress}%`}
                            </Text>
                        )}
                        <View style={styles.cardActions}>
                            {currentStage === 'ecg' && (
                                <TouchableOpacity
                                    style={[styles.skipButton, styles.cardButton]}
                                    onPress={skipCurrentStage}
                                >
                                    <Text style={styles.skipButtonText}>跳过</Text>
                                </TouchableOpacity>
                            )}
                            <TouchableOpacity
                                style={[styles.retestButton, styles.cardButton, {marginLeft: currentStage === 'ecg' ? 10 : 0}]}
                                onPress={() => {
                                    startHRVMeasurement();
                                }}
                            >
                                <Text style={styles.retestButtonText}>重测</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                {/*<View style={styles.saveButtonContainer}>*/}
                {/*    <TouchableOpacity*/}
                {/*        style={styles.saveButton}*/}
                {/*        onPress={() => {*/}
                {/*            if (measurement) {*/}
                {/*                // 保存规范化后的综合数据作为Cardiovascular类型，确保字段名统一*/}
                {/*                const normalizedMeasurement = createNormalizedCardiovascularMeasurement(measurement);*/}
                {/*                if (normalizedMeasurement) {*/}
                {/*                    addTestResult("Cardiovascular", "心血管检测仪", normalizedMeasurement);*/}
                {/*                }*/}
                {/*            }*/}
                {/*        }}*/}
                {/*    >*/}
                {/*        <Text style={styles.saveButtonText}>手动保存</Text>*/}
                {/*    </TouchableOpacity>*/}
                    {/*<TouchableOpacity*/}
                    {/*    style={[styles.saveButton, autoSaveEnabled ? styles.autoSaveOn : styles.autoSaveOff]}*/}
                    {/*    onPress={() => setAutoSaveEnabled(!autoSaveEnabled)}*/}
                    {/*>*/}
                    {/*    <Text style={styles.saveButtonText}>*/}
                    {/*        自动保存: {autoSaveEnabled ? '开' : '关'}*/}
                    {/*    </Text>*/}
                    {/*</TouchableOpacity>*/}
                {/*</View>*/}
            </>
        );
    };

    const GuideVideoComponent = () => (
        <View style={styles.videoContainer}>
            <ECGImageCarousel images={ecgImages} autoPlay={true} interval={4000} />
        </View>
    );

    const GuideTextComponent = ({type}: GuideTextComponentProps) => (
        <View style={styles.guideTextContainer}>
            <Text style={styles.guideTitle}>心血管检测操作指南</Text>
            <Text style={styles.guideStep}>1. 连接设备，等待指示灯变为绿色</Text>
            <Text style={styles.guideStep}>2. 佩戴血压袖带</Text>
            <Text style={styles.guideStep}>3. 将三个心电夹分别夹在左手腕，右手腕，左脚踝处。注意导电片贴住体内侧</Text>
            <Text style={styles.guideStep}>4. 将血氧探头夹在手指上</Text>
            <Text style={styles.guideStep}>5. 点击&#34;开始检测&#34;按钮</Text>
            <Text style={styles.guideStep}>6. 保持静止，等待测量完成</Text>
            <Text style={styles.guideTip}>提示：如遇压力/心康指数测量过程停滞，可轻旋调整心电夹（尤其是左踝处），以保证接触良好</Text>
        </View>
    );

    return (
        <View style={styles.container}>
            {/* 图片弹窗 */}
            <Modal
                visible={showImageModal}
                transparent={true}
                animationType="fade"
                onRequestClose={() => setShowImageModal(false)}
            >
                <View style={styles.imageModalOverlay}>
                    {currentImage === 1 && (
                        <Image
                            source={require('../../assets/images/1.png')}
                            style={styles.modalImage}
                            resizeMode="contain"
                        />
                    )}
                    {currentImage === 2 && (
                        <Image
                            source={require('../../assets/images/2.png')}
                            style={styles.modalImage}
                            resizeMode="contain"
                        />
                    )}
                </View>
            </Modal>
            
            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                        <View style={styles.dialogButtons}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.stayButton]}
                                onPress={() => setShowCompletionDialog(false)}
                            >
                                <Text style={styles.stayButtonText}>继续检测</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.returnButton]}
                                onPress={finishTest}
                            >
                                <Text style={styles.returnButtonText}>返回</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
            
            <View style={styles.header}>
                <Text style={styles.title}>{deviceName}</Text>
                <Text style={styles.subtitle}>请按照提示进行测量</Text>
            </View>

            <View style={styles.content}>
                <View style={styles.statusContainer}>
                    <View style={styles.statusInfo}>
                        <View style={[
                            styles.statusIndicator,
                            {backgroundColor: isConnected ? '#4CAF50' : '#F44336'}
                        ]}/>
                        <Text style={styles.statusText}>
                            {isConnected ? '已连接' : '未连接'}
                        </Text>
                        {autoSaveEnabled && (
                            <Text style={styles.autoSaveText}>
                                (自动保存)
                            </Text>
                        )}
                    </View>

                    {!isConnected && (
                        <TouchableOpacity
                            style={[
                                styles.connectButton,
                                (isLoading || isAutoConnecting) && styles.disabledConnectButton
                            ]}
                            onPress={() => connectDevice(deviceNamePrefix, false)}
                            disabled={isLoading || isAutoConnecting}
                        >
                            {(isLoading || isAutoConnecting) ? (
                                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                    <Text style={styles.connectButtonText}>自动连接中 </Text>
                                    <ActivityIndicator color="#FFFFFF" size={12}/>
                                </View>
                            ) : (
                                <Text style={styles.connectButtonText}>
                                    {isAutoConnecting ? '自动连接中...' : '连接设备'}
                                </Text>
                            )}
                        </TouchableOpacity>
                    )}
                </View>

                <View style={styles.dataContainer}>
                    <View style={styles.contentLayout}>
                        <View style={styles.guideSection}>
                            <Text style={styles.guideSectionTitle}>操作流程指引</Text>
                            <View style={styles.guideContent}>
                                <GuideTextComponent type="guideText"/>
                            </View>
                        </View>

                        <View style={styles.demoSection}>
                            <GuideVideoComponent/>
                            {/*<TouchableOpacity*/}
                            {/*    style={[styles.startButton, !isConnected && styles.disabledButton]}*/}
                            {/*    onPress={!isMeasuring ? startMeasurement : stopMeasurement}*/}
                            {/*    disabled={!isConnected || isLoading}*/}
                            {/*>*/}
                            {/*    {isLoading ? (*/}
                            {/*        <ActivityIndicator color="#FFFFFF"/>*/}
                            {/*    ) : (*/}
                            {/*        <Text style={styles.buttonText}>*/}
                            {/*            {!isMeasuring ? '开始检测' : '停止检测'}*/}
                            {/*        </Text>*/}
                            {/*    )}*/}
                            {/*</TouchableOpacity>*/}
                        </View>
                    </View>

                    <View style={styles.resultContainer}>
                        {renderResult()}
                    </View>
                </View>
            </View>
        </View>
    );

};

const styles = StyleSheet.create({
    // 进度显示相关样式
    modalOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    progressContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '85%',
        maxWidth: 400,
        alignItems: 'center',
    },
    progressTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 16,
    },
    stageText: {
        fontSize: 16,
        color: '#333',
        marginBottom: 20,
    },
    progressBarContainer: {
        width: '100%',
        height: 8,
        backgroundColor: '#e0e0e0',
        borderRadius: 4,
        marginBottom: 24,
        overflow: 'hidden',
    },
    progressBar: {
        height: '100%',
        backgroundColor: '#0a7ea4',
        borderRadius: 4,
    },
    stepsContainer: {
        width: '100%',
        marginBottom: 24,
    },
    stepItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 12,
    },
    stepIndicator: {
        width: 24,
        height: 24,
        borderRadius: 12,
        backgroundColor: '#e0e0e0',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 12,
    },
    stepIndicatorActive: {
        backgroundColor: '#0a7ea4',
    },
    stepIndicatorSkipped: {
        backgroundColor: '#ffc107',
    },
    stepNumber: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#666',
    },
    stepNumberActive: {
        color: 'white',
    },
    stepLabel: {
        fontSize: 14,
        color: '#666',
        flex: 1,
    },
    stepLabelActive: {
        color: '#333',
        fontWeight: 'bold',
    },
    skipButton: {
        backgroundColor: '#444',
        paddingVertical: 12,
        paddingHorizontal: 40,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.2,
        elevation: 3,
    },
    skipButtonDisabled: {
        backgroundColor: '#ccc',
    },
    skipButtonText: {
        color: 'white',
        fontSize: 16,
        fontWeight: 'bold',
    },
    container: {
        flex: 1,
        backgroundColor: '#f6f8fa',
    },
    header: {
        backgroundColor: '#0a7ea4',
        paddingTop: 20,
        paddingBottom: 20,
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        color: 'white',
        marginBottom: 8,
    },
    subtitle: {
        fontSize: 16,
        color: 'rgba(255,255,255,0.9)',
        textAlign: 'center',
    },
    content: {
        flex: 1,
        padding: 20,
    },
    statusContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,
        backgroundColor: 'white',
        padding: 12,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        elevation: 2,
    },
    statusInfo: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    statusIndicator: {
        width: 10,
        height: 10,
        borderRadius: 5,
        marginRight: 8,
    },
    statusText: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    autoSaveText: {
        fontSize: 12,
        color: '#666',
        marginLeft: 8,
    },
    connectButton: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 8,
        paddingHorizontal: 16,
        borderRadius: 4,
    },
    disabledConnectButton: {
        backgroundColor: '#6c757d',
    },
    connectButtonText: {
        color: 'white',
        fontSize: 14,
        fontWeight: 'bold',
    },
    dataContainer: {
        flex: 1,
    },
    contentLayout: {
        flexDirection: 'row',
        flex: 1,
        marginBottom: 20,
    },
    guideSection: {
        flex: 1,
        marginRight: 10,
        backgroundColor: 'white',
        padding: 12,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        elevation: 2,
    },
    guideSectionTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 10,
        textAlign: 'center',
    },
    guideContent: {
        flex: 1,
    },
    demoSection: {
        flex: 1,
        marginLeft: 10,
        backgroundColor: 'white',
        padding: 8,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        elevation: 2,
        flexDirection: 'column',
        justifyContent: 'space-between',
    },
    startButton: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 16,
        paddingHorizontal: 30,
        borderRadius: 8,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 15,
        marginBottom: 10,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.2,
        elevation: 3,
        minHeight: 50,
    },
    disabledButton: {
        backgroundColor: '#6c757d',
    },
    buttonText: {
        color: 'white',
        fontSize: 18,
        fontWeight: 'bold',
    },
    resultContainer: {
        backgroundColor: 'white',
        padding: 16,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        elevation: 2,
    },
    videoContainer: {
        width: '100%',
        flex: 1,
        alignItems: 'center',
        marginBottom: 15,
    },
    video: {
        width: '100%',
        height: 432,
        backgroundColor: 'black',
        borderRadius: 8,
    },
    guideTextContainer: {
        width: '100%',
        padding: 10,
    },
    guideTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 15,
        textAlign: 'center',
    },
    guideStep: {
        fontSize: 14,
        color: '#333',
        marginBottom: 8,
        lineHeight: 20,
    },
    guideTip: {
        fontSize: 14,
        color: '#0a7ea4',
        fontStyle: 'italic',
        marginTop: 10,
    },
    dataGrid: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        width: '100%',
        flexWrap: 'wrap',
    },
    dataCard: {
        flex: 1,
        minWidth: '30%',
        backgroundColor: '#f8f9fa',
        borderRadius: 8,
        padding: 12,
        alignItems: 'center',
        marginBottom: 10,
        marginHorizontal: 5,
    },
    combinedData: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 5,
    },
    separator: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginHorizontal: 8,
    },
    dataLabel: {
        fontSize: 14,
        color: '#333',
        marginBottom: 8,
        textAlign: 'center',
    },
    dataValue: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#0a7ea4',
    },
    unitSmall: {
        fontSize: 12,
        color: '#666',
        fontWeight: 'normal',
    },
    stValuesContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'center',
        alignItems: 'center',
    },
    cuffText: {
        fontSize: 12,
        color: '#666',
        marginTop: 4,
    },
    saveButtonContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginTop: 20,
        width: '100%',
    },
    retestButtonContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 15,
        marginBottom: 10,
    },
    retestButton: {
        backgroundColor: '#f58220',
        paddingVertical: 12,
        paddingHorizontal: 40,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.2,
        elevation: 3,
    },
    retestButtonText: {
        color: 'white',
        fontSize: 16,
        fontWeight: 'bold',
    },
    saveButton: {
        flex: 1,
        backgroundColor: '#0a7ea4',
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 5,
    },
    autoSaveOn: {
        backgroundColor: '#28a745',
    },
    autoSaveOff: {
        backgroundColor: '#6c757d',
    },
    saveButtonText: {
        color: 'white',
        fontSize: 14,
        fontWeight: 'bold',
    },
    // 状态指示器样式
    stageStatusContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 10,
    },
    stageLabel: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    statusIndicatorSmall: {
        paddingHorizontal: 8,
        paddingVertical: 4,
        borderRadius: 12,
        justifyContent: 'center',
        alignItems: 'center',
    },
    statusTextSmall: {
        fontSize: 12,
        fontWeight: '500',
        color: 'white',
    },
    statusIdle: {
        backgroundColor: '#757575',
    },
    statusMeasuring: {
        backgroundColor: '#2196F3',
    },
    statusCompleted: {
        backgroundColor: '#4CAF50',
    },
    statusSkipped: {
        backgroundColor: '#FF9800',
    },
    // 卡片操作按钮容器
    cardActions: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        marginTop: 10,
    },
    cardButton: {
        flex: 0,
        paddingHorizontal: 16,
        paddingVertical: 8,
    },
    // 图片弹窗样式
    imageModalOverlay: {
        flex: 1,
        backgroundColor: 'transparent',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalImage: {
        width: 300,
        height: 400,
    },
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
});

export default CardiovascularDevice;